

package com.developerlife.myservice;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;


public class LocalServiceBinding extends Activity {
    private boolean mIsBound;
    private LocalService mBoundService;
    Button mPlayButton;
    
    @Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.local_service_binding);
        Button button = (Button)findViewById(R.id.bind);
        button.setOnClickListener(mBindListener);
        button = (Button)findViewById(R.id.unbind);
        button.setOnClickListener(mUnbindListener);
        mPlayButton = (Button)findViewById(R.id.play);
        mPlayButton.setOnClickListener(mPlayListener);
        mPlayButton.setText("Play");
        mPlayButton.setEnabled(false);
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mBoundService = ((LocalService.LocalBinder)service).getService();            
            Toast.makeText(LocalServiceBinding.this, R.string.local_service_connected,
                    Toast.LENGTH_SHORT).show();
        }

        public void onServiceDisconnected(ComponentName className) {
            mBoundService = null;
            Toast.makeText(LocalServiceBinding.this, R.string.local_service_disconnected,
                    Toast.LENGTH_SHORT).show();
        }
    };

    private OnClickListener mBindListener = new OnClickListener() {
        public void onClick(View v) {
            bindService(new Intent(LocalServiceBinding.this, 
                    LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
            mIsBound = true;
            mPlayButton.setEnabled(true);
            
        }
    };

    private OnClickListener mPlayListener = new OnClickListener() {
        public void onClick(View v) {
        		if(mPlayButton.getText() == "Play")
        		{
        			mBoundService.startMp3Player();
        			mPlayButton.setText("Stop");
        		}
        		else
        		{
        			mBoundService.mp3Stop();
        			mPlayButton.setText("Play");
        		}	        	
        }
    };
    
    private OnClickListener mUnbindListener = new OnClickListener() {
        public void onClick(View v) {
            if (mIsBound) {
                unbindService(mConnection);
                mIsBound = false;
                mPlayButton.setEnabled(false);
            }
        }
    };
}

